package com.junko.admin.interceptor;

import com.junko.core.constant.ConstantWebContext;
import com.junko.core.exception.BusinessException;
import com.junko.core.tool.*;
import com.junko.model.back.Syslog;
import com.junko.service.app.IUserService;
import com.junko.service.back.ISyslogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class SystemInterceptor extends HandlerInterceptorAdapter {
//    private Logger logger = LoggerFactory.getLogger(SystemInterceptor.class);
    @Resource
    private ISyslogService sysLogService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

//        String actionKey = ToolWeb.getActionKey(request);
//        if (ToolSystem.isMobile(request) && StringUtils.startsWith(actionKey, "/f") && !StringUtils.startsWith(actionKey, "/file") && !StringUtils.equals(actionKey, "/")) {
//            throw new BusinessException("请使用电脑浏览器访问本页面");
//        }
//        if (ToolSystem.isPc(request) && StringUtils.startsWith(actionKey, "/app") && !StringUtils.equals(actionKey, "/app")) {
//            throw new BusinessException("请使用手机浏览器访问本页面");
//        }
        Syslog reqSyslog = getSyslog(request);
        long startTime = ToolDateTime.getDateByTime();
        reqSyslog.setStartDate(ToolDateTime.getSqlTimestamp(startTime));//开始时间
        request.setAttribute(ConstantWebContext.reqSyslogKey, reqSyslog);

//		log.info("设置 web 路径");
        String cxt = ToolWeb.getContextPath(request);
        request.setAttribute(ConstantWebContext.request_cxt, cxt);

//		log.info("request 随机分配一个请求id");
        request.setAttribute(ConstantWebContext.request_id, ToolRandoms.getUuid(true));

//		log.debug("request cookie 处理");
        Map<String, Cookie> cookieMap = ToolWeb.readCookieMap(request);
        request.setAttribute(ConstantWebContext.request_cookieMap, cookieMap);

//		log.debug("request param 请求参数处理");
        request.setAttribute(ConstantWebContext.request_paramMap, ToolWeb.getParamMap(request));

//		log.info("设置Header");
        request.setAttribute("decorator", "none");
        response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
        response.setHeader("Pragma", "no-cache"); //HTTP 1.0
        response.setDateHeader("Expires", 0); //prevents caching at the proxy server

//		log.info("请求处理完毕，计算耗时");

        // 结束时间
        long endTime = ToolDateTime.getDateByTime();
        reqSyslog.setEndDate(ToolDateTime.getSqlTimestamp(endTime));

        // 总耗时
        Long haoshi = endTime - startTime;
        reqSyslog.setHaoShi(haoshi);

        // 视图耗时
        long renderTime = 0;
        if (null != request.getAttribute(ConstantWebContext.renderTimeKey)) {
            renderTime = (long) request.getAttribute(ConstantWebContext.renderTimeKey);
        }
        reqSyslog.setViewHaoShi(renderTime);

        // action耗时
        reqSyslog.setActionHaoShi(haoshi - renderTime);

        request.setAttribute(ConstantWebContext.reqSyslogKey, reqSyslog);

        return true;
    }

    /**
     * 创建日志对象,并初始化一些属性值
     *
     * @param request
     * @return
     */
    public Syslog getSyslog(HttpServletRequest request) {
        String requestPath = ToolWeb.getRequestURL(request);
        String ip = ToolWeb.getIpAddr(request);
        String referer = request.getHeader("Referer");
        String userAgent = request.getHeader("User-Agent");
        String cookie = request.getHeader("Cookie");
        String method = request.getMethod();
        String xRequestedWith = request.getHeader("X-Requested-With");
        String host = request.getHeader("Host");
        String acceptLanguage = request.getHeader("Accept-Language");
        String acceptEncoding = request.getHeader("Accept-Encoding");
        String accept = request.getHeader("Accept");
        String connection = request.getHeader("Connection");

        Syslog reqSyslog = new Syslog();
        reqSyslog.setIp(ip);
        reqSyslog.setRequestPath(requestPath);
        reqSyslog.setReferer(referer);
        reqSyslog.setUserAgent(userAgent);
        reqSyslog.setCookie(cookie);
        reqSyslog.setMethod(method);
        reqSyslog.setxRequestedWith(xRequestedWith);
        reqSyslog.setHost(host);
        reqSyslog.setAcceptLanguage(acceptLanguage);
        reqSyslog.setAcceptEncoding(acceptEncoding);
        reqSyslog.setAccept(accept);
        reqSyslog.setConnection(connection);
        return reqSyslog;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
